import dayjs from 'dayjs'
import mongoose, { Document, Schema } from 'mongoose'

export interface IDynamicCollectionConfig extends Document {
  collectionName: string
  fields: {
    name: string
    type: 'String' | 'Number' | 'Boolean' | 'Date' | 'Array'
    required?: boolean
    defaultValue?: any
  }[]
  created_at: Date
  updated_at: Date
}

const DynamicCollectionConfigSchema = new Schema(
  {
    collectionName: {
      type: String,
      required: true,
      unique: true
    },
    fields: {
      type: [
        {
          name: {
            type: String,
            required: true
          },
          type: {
            type: String,
            required: true,
            enum: ['String', 'Number', 'Boolean', 'Date', 'Array']
          },
          required: {
            type: Boolean,
            default: false
          },
          defaultValue: {
            type: Schema.Types.Mixed,
            default: undefined
          }
        }
      ],
      required: true
    },
    created_at: {
      type: String,
      default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
      description: '创建时间'
    },
    updated_at: {
      type: String,
      default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
      description: '最后更新时间'
    },
  },
  {
    timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
  }
)

export const DynamicCollectionConfig = mongoose.model<IDynamicCollectionConfig>(
  'dynamic_collection_config',
  DynamicCollectionConfigSchema
)
